package org.yray.netty.lengthfield;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.checkerframework.checker.units.qual.A;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ChannelHandler.Sharable
public class NettyLengthFieldClientHandler extends ChannelInboundHandlerAdapter {

    private Channel channel;

    private TcpClient tcpClient;

    public TcpClient getTcpClient() {
        return tcpClient;
    }

    public void setTcpClient(TcpClient tcpClient) {
        this.tcpClient = tcpClient;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    /**
     * 当客户端连接服务器完成就会触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    private AtomicInteger atomicInteger=new AtomicInteger(0);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println ("发送消息");
        for (int i = 0; i < 2; i++) {
            //拆包用分隔符
            ByteBuf buf = Unpooled.copiedBuffer ("HelloServer"+i, CharsetUtil.UTF_8);
            ctx.writeAndFlush (buf);
        }
        //ctx.fireChannelActive ();
    }
    //当通道有读取事件时会触发，即服务端发送数据给客户端
    //msg就额是接受的消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       try{
           ByteBuf buf = (ByteBuf) msg;
           //因为已经使用了StringDecoder传过来的已经string类型
           System.out.println ("收到服务端的消息:" + buf);
           if(atomicInteger.incrementAndGet()%10 ==0 )
           {
               ctx.writeAndFlush ("helloclent:"+atomicInteger.get());
           }
       }
       catch (Throwable t)
       {
           System.out.println ("收到服务端的消息:err");
       }

    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace ();
        ctx.close ();
    }


    public void sendMsg(String msg)
    {

        try {
            if(channel.isActive()) {
                ByteBuf buf = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
                channel.writeAndFlush(buf);
            }
            else {
                System.out.println("已掉线，等待重连 ...");
            }
        }
        catch (Exception e)
        {
            System.out.println("waiting connect ...");
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        System.out.println("掉线了...");
        System.out.println("channelInactive:"+ ctx.channel().localAddress());
        try{
            super.channelInactive(ctx);
            tcpClient.connectAsync();
         //   System.out.println("重连完成");
        }catch (Exception e){
            System.out.println("重连失败:{}"+ ExceptionUtils.getStackTrace(e));
        }

    }
}
